package com.huahang.fashionpress.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huahang.fashionpress.convert.ProductVOConvertProduct;
import com.huahang.fashionpress.exception.ResultException;
import com.huahang.fashionpress.form.FormProduct;
import com.huahang.fashionpress.model.Category;

import com.huahang.fashionpress.model.Product;
import com.huahang.fashionpress.service.CategoryService;
import com.huahang.fashionpress.service.ImgService;
import com.huahang.fashionpress.service.ProductService;
import com.huahang.fashionpress.vo.ProductVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 *后台商品数据控制类
 * @Author: 阿俊哥
 * @Date: 2019/8/23 16:09
 * @Version 1.0
 */
@Controller
@Slf4j
@RequestMapping("/product")
public class AdminProductController {

    @Resource
    ProductService productService;
    @Resource
    ImgService imgService;
    @Resource
    CategoryService categoryService;

    /**
     * 返回商品的list方法
     * @param productStatus
     * @return
     */
    @RequestMapping("/list")
    public ModelAndView getProductList(@RequestParam(name = "productStatus",defaultValue = "0") int productStatus,
                                       @RequestParam(name = "size",defaultValue = "4") int size,
                                       @RequestParam(name = "pagenum",defaultValue = "1") int pagenum,
                                       Map<String,Object> map){
        List<ProductVO> productVOS = new ArrayList<>();
        Page<Product> products = productService.selectProductList(productStatus,size,pagenum);
        long totalPages = products.getTotal()/4+1;
        List<Product> productList = products.getRecords();
        for (Product product :productList) {
            ProductVO productVO = new ProductVO();
            BeanUtils.copyProperties(product, productVO);
            productVO.setImgs(imgService.selectImgList(product.getProductId()));
            productVO.setCategory(categoryService.SelectCategoryById(product.getCategoryId()));
            productVOS.add(productVO);
        }
        map.put("productVOs", productVOS);
        map.put("productStatus", productStatus);
        map.put("pagenum", pagenum);
        map.put("totalPage", totalPages);
        return new ModelAndView("admin/product/list",map);

    }

    /**
     * 根据id进行查询商品
     * @param productId
     * @param map
     * @return
     */
    @RequestMapping("/selectById/{productId}")
    public ModelAndView getProductById(@PathVariable String productId, Map<String,Object> map){
        Product product = productService.selectProductById(productId);
        List<String> imgs = imgService.selectImgList(productId);
        Category category = categoryService.SelectCategoryById(product.getCategoryId());
        ProductVO productVO = ProductVOConvertProduct.productVOConvertProduct(product,imgs,category);
        List<ProductVO> productVOS = new ArrayList<>();
        productVOS.add(productVO);
        map.put("productVOs", productVOS);
        return new ModelAndView("/admin/product/list", map);
    }

    /**
     * 根据商品名称进行查询，返回值可以有多个
     * @param productName
     * @param map
     * @return
     */
    @RequestMapping("/selectByName/{productName}")
    public ModelAndView getProductByName(@PathVariable String productName, Map<String,Object> map){
        List<Product> productList = productService.selectProductByName(productName);
        List<ProductVO> productVOS = new ArrayList<>();
        for (Product product:productList) {
            List<String> imgs = imgService.selectImgList(product.getProductId());
            Category category = categoryService.SelectCategoryById(product.getCategoryId());
            ProductVO productVO = ProductVOConvertProduct.productVOConvertProduct(product,imgs,category);
            productVOS.add(productVO);
        }
        map.put("productVOs", productVOS);
        return new ModelAndView("redirect:/product/list", map);
    }

    /**
     * 进行商品信息的修改，不可以修改id,销量不可以更改
     * @param productId
     * @param map
     * @return
     */
    @RequestMapping(value = "/update/{productId}",method = RequestMethod.GET)
    public ModelAndView updateProduct(@PathVariable String productId,Map<String,Object> map){
        //找到product
        Product product = productService.selectProductById(productId);
        //找到所在的分类
        Category category = categoryService.SelectCategoryById(product.getCategoryId());
        //找到所有的分类
        FormProduct formProduct = ProductVOConvertProduct.productFormConvertProduct(product);
        List<Category> categorys = categoryService.SelectallCategory();
        map.put("formProduct", formProduct);
        map.put("categorys", categorys);
        return new ModelAndView("/admin/product/add", map);
    }

    /**
     * 进行商品的添加操作，返回到添加页面
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public ModelAndView updateProduct(Map<String,Object> map){
        List<Category> categorys = categoryService.SelectallCategory();
        map.put("categorys", categorys);

        return new ModelAndView("/admin/product/add",map);
    }

    /**
     * 处理商品的添加和修改操作
     * @param formProduct
     * @param bindingResult
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public ModelAndView updateProduct(@Valid FormProduct formProduct, BindingResult bindingResult, Map<String ,Object> map, HttpServletRequest request){
        if(bindingResult.hasErrors()){
            log.info("【商品管理】商品修改出现数据错误");
            throw new ResultException(500,bindingResult.getFieldError().toString());
        }
        if(formProduct.getProductId()==null){
            //添加商品信息
            Product product = new Product();
            BeanUtils.copyProperties(formProduct,product);
            //给销售额赋初值
            product.setProductSales(0);
            productService.addProduct(product,request);
            map.put("msg", "商品添加成功");
            map.put("url", "/fashionpress/product/list");
            return new ModelAndView("/admin/common/success",map);
        }
        Product product = productService.selectProductById(formProduct.getProductId());
        product.setCategoryId(formProduct.getCategoryId());
        product.setProductDescribe(formProduct.getProductDescribe());
        product.setProductInventory(formProduct.getProductInventory());
        product.setProductName(formProduct.getProductName());
        product.setProductPrice(formProduct.getProductPrice());
        product.setProductStatus(formProduct.getProductStatus());
        productService.updateProduct(product);
        map.put("msg", "商品信息修改成功");
        map.put("url", "/fashionpress/product/list");
        return new ModelAndView("/admin/common/success",map);


    }

    @RequestMapping("/updateProductStatus/{productId}")
    public ModelAndView updateProductStatus(@PathVariable String productId,  Map<String,Object> map){
        productService.updateProductStatus(productId);
        map.put("msg", "商品状态修改成功");
        map.put("url", "/fashionpress/product/list");
        return new ModelAndView("/admin/common/success",map);

    }
}
